﻿/*
 * Created by SharpDevelop.
 * User: mac
 * Date: 26.01.2007
 * Time: 17:28
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TagTool.Core;
using TagTool.GraphicTypes;
using System.IO;

namespace TagTool.Nodes.Misc
{
	public class LoadFile : BaseNode
	{
		private InputSlot fileName;
		private OutputSlot shape;
		private bool tin;
		
		public LoadFile()
		{
			this.Name = "LoadFile";
			shape = new OutputSlot(this, "Shape", typeof(Shape));
			shape.Value = new Shape();
			
			fileName = new InputSlot(this, "Filename", "");
			fileName.ParseCallback = ParseHelper.ParseString;
		}
		
		public override void Update(Object sender)
		{
			if ((bool)TriggerIn.Value != tin && shape.Value != null)
			{
				String path = ProjectManager.Instance.AppDir + "\\sessions\\" + ProjectManager.Instance.SessionName;
				string fn = path + "\\" + (String)fileName.Value;
				
				Console.WriteLine(fn);
				Stream stream = null;
				try {
					stream = File.Open(fn, FileMode.Open);
					StreamReader reader = new StreamReader(stream);
					
					TagTool.GraphicTypes.Shape sh;
					if (TagTool.GraphicTypes.Shape.ReadHeader(reader, false, "Scene"))
					{
						sh = new Scene();
					}
					else if (TagTool.GraphicTypes.Shape.ReadHeader(reader, false, "Tag"))
					{
						sh = new Tag();
					} else
					{
						sh = new Tag();
					}
					
					//Console.WriteLine("new tag");
					sh.Load(reader);
					//Console.WriteLine("loaded");
					
					shape.Value = sh;
					
					if (TagTool.GraphicTypes.Shape.ReadHeader(reader, false, "Metadata"))
					{
						ProjectManager.Instance.UI.MetaData = reader.ReadLine();
					}
					
					//Console.WriteLine("and set" + tag.Lines.Count);
					
					CastTrigger();
				} 
				catch (Exception ex)
				{
					Console.WriteLine("Error: " + ex.StackTrace + " Filename = " + (String)fileName.Value);
				}
				finally {
					if (stream != null)
					{
						stream.Close();
					}
				}
			}
			
			tin = (bool)TriggerIn.Value;
		}
		
		[NodeAttribute(SlotType.Output, Show = true)]
        public OutputSlot Shape
        {
            get { return shape; }
        }
        
        [NodeAttribute(SlotType.Input, Show = true)]
        public InputSlot FileName
        {
            get { return fileName; }
        }
		
	}
}
